import time
import re
import json

if __name__ == '__main__':
    '''
    tup = (1, 2, 3, 4)
    new_tup = tup + (5, ) # 创建新的元组new_tup，并依次填充原元组的值
    print(new_tup)
    print(new_tup[-1])

    l = [1, 2, 3, 4]
    l.append(5)
    print(l)
    print(l[-1])
    '''

    '''
    l = [1, 2, 3, 4]
    print(l[1:3])

    tup = (1, 2, 3, 4)
    print(tup[1:3])
    '''

    '''
    l = [[1, 2, 3], [4, 5]]
    print(l)

    tup = ((1, 2, 3), (4, 5, 6))
    print(tup)
    '''

    '''
    print(list((1, 2, 3)))
    print(tuple([1, 2, 3]))
    '''

    '''
    l = [3, 2, 3, 7, 8, 1]
    print(l.count(3))
    print(l.index(7))
    l.reverse()
    print(l)
    l.sort()
    print(l)
    '''

    '''
    tup = (3, 2, 3, 7, 8, 1)
    print(tup.count(3))
    print(tup.index(7))
    print(list(reversed(tup)))
    print(sorted(tup))
    '''

    '''
    l = [1, 2, 3]
    print(l.__sizeof__())

    tup = (1, 2, 3)
    print(tup.__sizeof__())
    '''

    '''
    l = []
    print(l.__sizeof__()) # 空列表的存储空间为40字节
    l.append(1)
    print(l.__sizeof__()) # 加入了元素1之后，列表为其分配了可以存储4个元素的空间 (72 - 40)/8 = 4
    l.append(2)
    print(l.__sizeof__()) # 由于之前分配了空间，所以加入元素2，列表空间不变
    l.append(3)
    print(l.__sizeof__()) # 同上
    l.append(4)
    print(l.__sizeof__()) # 同上
    l.append(5)
    print(l.__sizeof__()) # 加入元素5之后，列表的空间不足，所以又额外分配了可以存储4个元素的空间
    '''

    '''
    empty_list = list() # list()是一个function call，Python的function call会创建stack，并且进行一系列参数检查的操作，比较expensive
    empty_list1 = [] # []是一个内置的C函数，可以直接被调用，因此效率高
    '''

    '''
    d1 = {'name': 'jason', 'age': 20, 'gender': 'male'}
    d2 = dict({'name': 'jason', 'age': 20, 'gender': 'male'})
    d3 = dict([('name', 'jason'), ('age', 20), ('gender', 'male')])
    d4 = dict(name='jason', age=20, gender='male')
    print(d1 == d2 == d3 == d4)

    s1 = {1, 2, 3}
    s2 = set([1, 2, 3])
    print(s1 == s2)
    '''

    '''
    s = {1, 'hello', 5.0}
    print(s)
    '''

    '''
    d = {'name': 'jason', 'age': 20}
    print(d['name'])
    print(d['location'])
    '''

    '''
    d = {'name': 'jason', 'age': 20}
    print(d.get('name'))
    print(d.get('location', 'null'))
    '''

    '''
    s = {1, 2, 3}
    print(s[0])
    '''

    '''
    s = {1, 2, 3}
    print(1 in s)
    print(10 in s)
    '''

    '''
    d = {'name': 'jason', 'age': 20}
    print('name' in d)
    print('location' in d)
    '''

    '''
    d = {'name': 'jason', 'age': 20}
    d['gender'] = 'male'
    d['dob'] = '1999-02-01'
    print(d)
    d['dob'] = '1998-01-01'
    print(d)
    d.pop('dob') # 删除键为'dob'的元素对
    print(d)

    s = {1, 2, 3}
    s.add(4)
    print(s)
    s.remove(4)
    print(s)
    s.pop() # 删除集合中最后一个元素，可是集合本身是无序的，你无法知道会删除哪个元素，因此这个操作得谨慎使用
    print(s)
    '''

    '''
    d = {'b': 1, 'a': 2, 'c': 3}
    d_sorted_by_key = sorted(d.items(), key=lambda x: x[0]) # 根据字典键的升序排序
    d_sorted_by_value = sorted(d.items(), key=lambda x: x[1]) # 根据字典值的升序排序
    print(d_sorted_by_key)
    print(d_sorted_by_value)
    '''

    '''
    s = {3, 4, 2, 1}
    sorted(s)
    print(s)
    '''

    '''
    def find_product_price(products, product_id):
        for id, price in products:
            if id == product_id:
                return price
        return None

    products = [
        (143121312, 100),
        (432314553, 30),
        (32421912367, 150)
    ]
    
    print('The price of product 432314553 is {}'.format(find_product_price(products, 432314553)))
    '''

    '''
    products = {
        143121312: 100,
        432314553: 30,
        32421912367: 150
    }

    print('The price of product 432314553 is {}'.format(products[432314553]))
    print('The price of product 432314553 is {}'.format(products.get(432314553)))
    '''

    '''
    # list version
    def find_unique_price_using_list(products):
        unique_price_list = []
        for _, price in products:
            if price not in unique_price_list:
                unique_price_list.append(price)
        return len(unique_price_list)

    # set version
    def find_unique_price_using_set(products):
        unique_price_set = set()
        for _, price in products:
            unique_price_set.add(price)
        return len(unique_price_set)

    products = [
        (143121312, 100),
        (432314553, 30),
        (32421912367, 150),
        (937153201, 30)
    ]
    print('number of unique price is: {}'.format(find_unique_price_using_list(products)))
    print('number of unique price is: {}'.format(find_unique_price_using_set(products)))

    id = [x for x in range(0, 100000)]
    price = [x for x in range(200000, 300000)]
    products = list(zip(id, price))

    # 计算列表版本的时间
    start_using_list = time.perf_counter()
    count1 = find_unique_price_using_list(products)
    end_using_list = time.perf_counter()
    print(count1)
    print("time elapse using list: {}".format(end_using_list - start_using_list))

    # 计算集合版本的时间
    start_using_set = time.perf_counter()
    count2 = find_unique_price_using_set(products)
    end_using_set = time.perf_counter()
    print(count2)
    print("time elapse using set: {}".format(end_using_set - start_using_set))
    '''

    '''
    name = 'jason'
    city = 'beijing'
    text = "welcome to jike shijian"

    s1 = 'hello'
    s2 = "hello"
    s3 = """hello"""
    print(s1 == s2 == s3)

    s = "I'm a student"
    print(s)
    '''

    '''
    s = 'a\nb\tc'
    print(s)
    print(len(s))
    '''

    '''
    name = 'jason'
    print(name[0])
    print(name[1:3])
    for char in name:
        print(char)
    '''

    '''
    s = 'hello'
    s[0] = 'H'
    '''

    '''
    s = 'hello'
    s1 = s.replace('h', 'H')
    print(s1)
    s2 = 'H' + s[1:]
    print(s2)
    '''

    '''
    s = ''
    for n in range(0, 100000):
        s += str(n)
    print(s)
    '''

    '''
    l = []
    for n in range(0, 100000):
        l.append(str(n))
    l = ''.join(l)
    print(l)
    '''

    '''
    path = 'hive://ads/training_table'
    namespace = path.split('//')[1].split('/')[0]
    print(namespace)
    table = path.split('//')[1].split('/')[1]
    print(table)
    '''

    '''
    s = '  my name is jason  '
    print(s.strip())
    print(s.lstrip())
    print(s.rstrip())
    '''

    '''
    print('no data available for person with id: {}, name:{}'.format(123, 'jason'))
    print('no data available for person with id: %d, name:%s' % (123, 'jason'))
    '''

    '''
    s = "".join(map(str, range(0, 10000)))
    print(s)
    '''

    '''
    name = input('your name: ')
    gender = input('you are a boy? (y/n) ')

    welcom_str = 'Welcome to the matrix {prefix} {name}.'
    welcome_dic = {
        'prefix': 'Mr.' if gender == 'y' else 'Mrs',
        'name': name
    }

    print('authorizing...')
    print(welcom_str.format(**welcome_dic))
    '''

    '''
    a = input()
    b = input()
    print('a + b = {}'.format(a + b))
    print('type of a is {}, type of b is {}'.format(type(a), type(b)))
    print('a + b = {}'.format(int(a) + int(b)))
    '''

    '''
    def parse(text):
        # 使用正则表达式去除标点符号和换行
        text = re.sub(r'[^\w]', ' ', text)

        # 转为小写
        text = text.lower();

        # 生成所有单词的列表
        word_list = text.split(' ')

        # 去除空白单词
        word_list = filter(None, word_list)

        # 生成单词和词频的字典
        word_cnt = {}
        for word in word_list:
            if word not in word_cnt:
                word_cnt[word] = 0
            word_cnt[word] += 1

        # 按照词频排序
        sorted_word_cnt = sorted(word_cnt.items(), key=lambda kv: kv[1], reverse=True)
        return sorted_word_cnt

    with open('/Users/wangjianwen/work/pythonProjects/py-test/asset/in.txt', 'r') as fin:
        text = fin.read()

    word_and_freq = parse(text)

    with open('/Users/wangjianwen/work/pythonProjects/py-test/asset/out.txt', 'w') as fout:
        for word, freq in word_and_freq:
            fout.write('{} {}\n'.format(word, freq))
    '''

    '''
    params = {
        'symbol': '123456',
        'type': 'limit',
        'price': 123.4,
        'amount': 23
    }

    params_str = json.dumps(params)
    print('after json serialization')
    print('type of params_str = {}, params_str = {}'.format(type(params_str), params_str))

    original_params = json.loads(params_str)
    print('after json deserialization')
    print('type of original_params = {}, original_params={}'.format(type(original_params), original_params))
    '''

    '''
    params = {
        'symbol': '123456',
        'type': 'limit',
        'price': 123.4,
        'amount': 23
    }

    with open('/Users/wangjianwen/work/pythonProjects/py-test/asset/params.json', 'w') as fout:
        params_str = json.dump(params, fout)

    with open('/Users/wangjianwen/work/pythonProjects/py-test/asset/params.json', 'r') as fin:
        original_params = json.load(fin)

    print('after json deserialization')
    print('type of original_params = {}, original_params={}'.format(type(original_params), original_params))
    '''

    '''
    CHUNK_SIZE = 100 # 这个数表示一次最多读取的字符长度

    # 这个函数每次会接收上一次得到的 last_word，然后和这次的 text 合并起来处理。
    # 合并后判断最后一个词有没有可能连续，并分离出来，然后返回。
    # 这里的代码没有 if 语句，但是仍然是正确的，可以想一想为什么。
    def parse_to_word_list(text, last_word, word_list):
        text = re.sub(r'[^\w]', ' ', last_word + text)
        text = text.lower()
        cur_word_list = text.split(' ')
        cur_word_list, last_word = cur_word_list[:-1], cur_word_list[-1]
        word_list += filter(None, cur_word_list)
        return last_word

    def solve():
        with open('/Users/wangjianwen/work/pythonProjects/py-test/asset/in.txt', 'r') as fin:
            word_list, last_word = [], ''
            while True:
                text = fin.read(CHUNK_SIZE)
                if not text:
                    break # 读取完毕，中断循环
                last_word = parse_to_word_list(text, last_word, word_list)

            word_cnt = {}
            for word in word_list:
                if word not in word_cnt:
                    word_cnt[word] = 0
                word_cnt[word] += 1

            sorted_word_cnt = sorted(word_cnt.items(), key=lambda kv: kv[1], reverse=True)
            return sorted_word_cnt

    print(solve())
    '''

    '''
    x = -5
    if x < 0:
        y = -x
    else:
        y = x
    print(y)
    '''

    '''
    id = input('please input: ')
    id = int(id)
    if id == 0:
        print('red')
    elif id == 1:
        print('yellow')
    else:
        print('green')
    '''

    '''
    l = [1, 2, 3, 4]
    for item in l:
        print(item)
    '''

    '''
    d = {'name': 'jason', 'dob': '2000-01-01', 'gender': 'male'}
    for k in d: # 遍历字典的键
        print(k)

    for v in d.values(): # 遍历字典的值
        print(v)

    for k, v in d.items(): # 遍历字典的键值对
        print('key: {}, value: {}'.format(k, v))
    '''

    '''
    l = [1, 2, 3, 4, 5, 6, 7]
    for index in range(0, len(l)):
        if index < 5:
            print(l[index])

    for index, item in enumerate(l):
        if index < 5:
            print(item)
            print('index: {}, value: {}'.format(index, item))
    '''

    '''
    l = [1, 2, 3, 4]
    index = 0
    while index < len(l):
        print(l[index])
        index += 1
    '''

    '''
    x = [1, -5, 8, 3]
    y = [value * 2 + 5 if value > 0 else -value * 2 + 5 for value in x]
    print(y)
    '''

    '''
    text = ' Today,  is, Sunday'
    text_list = [s.strip() for s in text.split(',') if len(s.strip()) > 3]
    print(text_list)
    '''

    '''
    x = [1, 3, 5, 7, 9]
    y = [3, 6, 9]
    print([(xx, yy) for xx in x for yy in y if xx != yy])

    l = []
    for xx in x:
        for yy in y:
            if xx != yy:
                l.append((xx, yy))
    print(l)
    '''

    '''
    attributes = ['name', 'dob', 'gender']
    values = [
        ['jason', '2000-01-01', 'male'],
        ['mike', '1999-01-01', 'male'],
        ['nancy', '2001-02-01', 'female']
    ]

    print([dict(zip(attributes, value)) for value in values])

    result_list = []
    for value in values:
        result_dict = {}
        for index, key in enumerate(attributes):
            result_dict[key] = value[index]
        result_list.append(result_dict)
    print(result_list)
    '''

    '''
    try:
        s = input('please enter two numbers separated by comma: ')
        num1 = int(s.split(',')[0].strip())
        num2 = int(s.split(',')[1].strip())
        print(num1 + num2)
    except (ValueError, IndexError) as err:
        print('Value Error: {}'.format(err))
    print('continue')
    '''

    '''
    try:
        s = input('please enter two numbers separated by comma: ')
        num1 = int(s.split(',')[0].strip())
        num2 = int(s.split(',')[1].strip())
        print(num1 + num2)
    except ValueError as err:
        print('Value Error: {}'.format(err))
    except IndexError as err:
        print('Index Error: {}'.format(err))
    except Exception as err:
        print('Other error: {}'.format(err))
    # except:
    #     print('Other error')
    # finally:
    #     f.close()
    print('continue')
    '''

    '''
    class MyInputError(Exception):
        """Exception raised when there're errors in input"""
        def __init__(self, value): # 自定义异常类型的初始化
            self.value = value
        def __str__(self): # 自定义异常类型的string表达形式
            return ("{} is invalid input".format(repr(self.value)))

    try:
        raise MyInputError(1) # 抛出MyInputError这个异常
    except MyInputError as err:
        print('error: {}'.format(err))
    '''
